﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EazyCMS.Common;

namespace EazyCMS.Web.Plugin.Vote.admin
{
    public partial class vote_edit : EazyCMS.Web.UI.ManagePage
    {
        private string action = EazyEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = EazyRequest.GetQueryString("action");

            if (!string.IsNullOrEmpty(_action) && _action == EazyEnums.ActionEnum.Edit.ToString())
            {
                this.action = EazyEnums.ActionEnum.Edit.ToString();//修改类型
                this.id = EazyRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    return;
                }
                if (!new BLL.vote().Exists(this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("plugin_vote", EazyEnums.ActionEnum.View.ToString()); //检查权限
                TreeBind(); //绑定站点
                if (action == EazyEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
            }
        }

        #region 绑定站点=================================
        private void TreeBind()
        {
            int parent_id = 0;
            EazyCMS.BLL.article_category bllzt = new EazyCMS.BLL.article_category();
            EazyCMS.BLL.channel_site bll = new EazyCMS.BLL.channel_site();
            DataTable dt = bll.GetList(0, "", "sort_id asc,id desc").Tables[0];

            this.ddlSitePath.Items.Clear();
            this.ddlSitePath.Items.Add(new ListItem("请选择站点...", ""));
            foreach (DataRow dr in dt.Rows)
            {
                this.ddlSitePath.Items.Add(new ListItem(dr["title"].ToString(), dr["build_path"].ToString()));
            }
            ddlSitePath.SelectedValue = "statistics";
            ////所属专题
            ////专题绑定
            ////专题
            //DataTable oldData = bllzt.GetList(0, 0, "");
            ////复制结构
            //DataTable newData = oldData.Clone();
            ////调用迭代组合成DAGATABLE
            //GetChilds(oldData, newData, parent_id);
            //DataTable dtz = newData;
            //this.ddspecial.Items.Clear();
            //this.ddspecial.Items.Add(new ListItem("所有专题", "0"));
            //foreach (DataRow dr in dtz.Rows)
            //{
            //    string Id = dr["id"].ToString();
            //    int ClassLayer = int.Parse(dr["class_layer"].ToString());
            //    string Title = dr["title"].ToString().Trim();

            //    if (ClassLayer == 1)
            //    {
            //        this.ddspecial.Items.Add(new ListItem(Title, Id));
            //    }
            //    else
            //    {
            //        Title = "├ " + Title;
            //        Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
            //        this.ddspecial.Items.Add(new ListItem(Title, Id));
            //    }
            //    //this.ddspecial.Items.Add(new ListItem(Title, Id));

            //}
        }

        /// <summary>
        /// 从内存中取得所有下级类别列表（自身迭代）
        /// </summary>
        private void GetChilds(DataTable oldData, DataTable newData, int parent_id)
        {
            DataRow[] dr = oldData.Select("parent_id=" + parent_id);
            for (int i = 0; i < dr.Length; i++)
            {
                //添加一行数据
                DataRow row = newData.NewRow();
                row["id"] = int.Parse(dr[i]["id"].ToString());
                row["parent_id"] = int.Parse(dr[i]["parent_id"].ToString());
                row["title"] = dr[i]["title"].ToString();
                row["describe"] = dr[i]["describe"].ToString();
                row["click_count"] = int.Parse(dr[i]["click_count"].ToString());
                row["class_layer"] = int.Parse(dr[i]["class_layer"].ToString());
                row["cover_url"] = dr[i]["cover_url"].ToString();
                row["vote_id"] = int.Parse(dr[i]["vote_id"].ToString());
                row["feed_id"] = int.Parse(dr[i]["feed_id"].ToString());
                row["channelid"] = int.Parse(dr[i]["channelid"].ToString());
                row["sort_id"] = int.Parse(dr[i]["sort_id"].ToString());
                row["site_path"] = dr[i]["site_path"].ToString();
                row["templete_url"] = dr[i]["templete_url"].ToString();
                row["add_time"] = DateTime.Parse(dr[i]["add_time"].ToString());

                newData.Rows.Add(row);
                //调用自身迭代
                this.GetChilds(oldData, newData, int.Parse(dr[i]["id"].ToString()));
            }
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            BLL.vote bll = new BLL.vote();
            Model.vote model = bll.GetModel(_id);

            ddlSitePath.SelectedValue = model.site_path;
            txtSortId.Text = model.sort_id.ToString();
            //ddspecial.SelectedValue = model.special_id.ToString();
            txtTitle.Text = model.title;
            txtTimu.Text = model.timu;
            rblIsMulti.SelectedValue = model.is_multi.ToString();
            txtStartTime.Text = model.start_time.ToString("yyyy-MM-dd");
            txtEndTime.Text = model.end_time.ToString("yyyy-MM-dd");
            txtContent.Value = model.content;
            //绑定投票选项
            rptList.DataSource = model.options;
            rptList.DataBind();
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            bool result = false;
            Model.vote model = new Model.vote();
            BLL.vote bll = new BLL.vote();

            model.site_path = ddlSitePath.SelectedValue;
            model.sort_id = Utils.StrToInt(txtSortId.Text.Trim(), 99);
            model.title = txtTitle.Text.Trim();
            model.timu = txtTimu.Text.Trim();
            model.is_multi = Utils.StrToInt(rblIsMulti.SelectedValue, 0);
            model.start_time = DateTime.Parse(this.txtStartTime.Text.Trim());
            model.end_time = DateTime.Parse(this.txtEndTime.Text.Trim());
            model.content = txtContent.Value;
            //if (ddspecial.SelectedValue != "0")
            //{
            //    model.is_special = 1;//为专题选项
            //}
            //else
            //{
            //    model.is_special = 0;//不是专题

            //}
            //model.special_id = Convert.ToInt32(ddspecial.SelectedValue);

            #region 保存投票选项
            string[] itemIdArr = Request.Form.GetValues("item_id");
            string[] itemTitleArr = Request.Form.GetValues("item_title");
            string[] itemTimuArr = Request.Form.GetValues("item_timu");
            string[] itemNumArr = Request.Form.GetValues("item_num");
            string[] itemSortIdArr = Request.Form.GetValues("item_sortid");
            if (itemIdArr != null && itemTitleArr != null && itemTimuArr != null && itemNumArr != null && itemSortIdArr != null)
            {
                if ((itemIdArr.Length == itemTitleArr.Length) && (itemTitleArr.Length == itemNumArr.Length) && (itemTimuArr.Length == itemNumArr.Length) && (itemNumArr.Length == itemSortIdArr.Length))
                {
                    List<Model.vote_option> ls = new List<Model.vote_option>();
                    for (int i = 0; i < itemIdArr.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(itemIdArr[i].Trim()))
                        {
                            Model.vote_option modelt = new Model.vote_option();
                            modelt.id = Utils.StrToInt(itemIdArr[i].Trim(), 0);
                            modelt.title = itemTitleArr[i].Trim();
                            modelt.timu = itemTimuArr[i].Trim();
                            modelt.vote_num = Utils.StrToInt(itemNumArr[i].Trim(), 0);
                            modelt.sort_id = Utils.StrToInt(itemSortIdArr[i].Trim(), 99);
                            ls.Add(modelt);
                        }
                    }
                    model.options = ls;
                }
            }
            #endregion
            
            if (bll.Add(model) > 0)
            {
                AddAdminLog(EazyEnums.ActionEnum.Add.ToString(), "添加投票主题：" + model.title); //记录日志
                result = true;
            }
            return result;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            bool result = false;
            BLL.vote bll = new BLL.vote();
            Model.vote model = bll.GetModel(_id);

            model.site_path = ddlSitePath.SelectedValue;
            model.sort_id = Utils.StrToInt(txtSortId.Text.Trim(), 99);
            model.title = txtTitle.Text.Trim();
            model.timu = txtTimu.Text.Trim();
            model.is_multi = Utils.StrToInt(rblIsMulti.SelectedValue, 0);
            model.start_time = DateTime.Parse(this.txtStartTime.Text.Trim());
            model.end_time = DateTime.Parse(this.txtEndTime.Text.Trim());
            model.content = txtContent.Value;
            //if (ddspecial.SelectedValue != "0")
            //{
            //    model.is_special = 1;
            //}
            //else
            //{
            //    model.is_special = 0;
            //}
            //model.special_id = Convert.ToInt32(ddspecial.SelectedValue);
            #region 保存投票选项
            string[] itemIdArr = Request.Form.GetValues("item_id");
            string[] itemTitleArr = Request.Form.GetValues("item_title");
            string[] itemTimuArr = Request.Form.GetValues("item_timu");
            string[] itemNumArr = Request.Form.GetValues("item_num");
            string[] itemSortIdArr = Request.Form.GetValues("item_sortid");
            if (itemIdArr != null && itemTitleArr != null && itemTimuArr != null && itemNumArr != null && itemSortIdArr != null)
            {
                if ((itemIdArr.Length == itemTitleArr.Length) && (itemTitleArr.Length == itemNumArr.Length) && (itemTimuArr.Length == itemNumArr.Length) && (itemNumArr.Length == itemSortIdArr.Length))
                {
                    List<Model.vote_option> ls = new List<Model.vote_option>();
                    for (int i = 0; i < itemIdArr.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(itemIdArr[i].Trim()))
                        {
                            Model.vote_option modelt = new Model.vote_option();
                            modelt.id = Utils.StrToInt(itemIdArr[i].Trim(), 0);
                            modelt.vote_id = model.id;
                            modelt.title = itemTitleArr[i].Trim();
                            modelt.timu = itemTimuArr[i].Trim();
                            modelt.vote_num = Utils.StrToInt(itemNumArr[i].Trim(), 0);
                            modelt.sort_id = Utils.StrToInt(itemSortIdArr[i].Trim(), 99);
                            ls.Add(modelt);
                        }
                    }
                    model.options = ls;
                }
            }
            #endregion

            if (bll.Update(model))
            {
                AddAdminLog(EazyEnums.ActionEnum.Edit.ToString(), "修改投票主题：" + model.title); //记录日志
                result = true;
            }

            return result;
        }
        #endregion

        //保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == EazyEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("plugin_vote", EazyEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", string.Empty);
                    return;
                }
                JscriptMsg("修改在线投票成功！", "index.aspx");
            }
            else //添加
            {
                ChkAdminLevel("plugin_vote", EazyEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", string.Empty);
                    return;
                }
                JscriptMsg("添加在线投票成功！", "index.aspx");
            }
        }

    }
}